﻿using Dapper;
using Sql_Windows_Sp_Tools.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace Sql_Windows_Sp_Tools.Repository
{
    public class ProcedureRep
    {
        private string _DBConn;
        public ProcedureRep(string DBConn)
        {
            _DBConn = DBConn;
        }
        /// <summary>
        /// 存储过程是否存在
        /// </summary>
        /// <param name="ProcedureName">存储过程名称</param>
        /// <returns>1.已删除存在存储过程，2.无存储过程</returns>
        public int IsExists(string ProcedureName = "sp_test")
        {
            var sql = @$"
IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = object_id( N'{ProcedureName}' ) AND OBJECTPROPERTY( id, N'IsProcedure' ) = 1 ) 
BEGIN
    drop procedure {ProcedureName} --删除 
    SELECT 1 --删除存储过程后添加
END 
ELSE 
BEGIN
    SELECT 2 --直接添加
END
";
            using (IDbConnection db = new SqlConnection(_DBConn))
            {
                return db.ExecuteScalar<int>(sql);
            }
        }

        public int Create(string sql)
        {
            using (IDbConnection db = new SqlConnection(_DBConn))
            {
                return db.ExecuteScalar<int>(sql);
            }
        }
    }
}
